package imageUtility;


import imageClassifying.IDistance;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class KNN {
	IDistance disCalc;
	
	public KNN(IDistance disCalc){
		this.disCalc = disCalc;
	}
	
	private List<ImageDistancePair> SortDistances(ImageData image, List<ImageData> imageSet) {
		ArrayList<ImageDistancePair> distanceList = new ArrayList<ImageDistancePair>();
		
		for (ImageData currImage : imageSet) {
			double distance = disCalc.calculateDistance(image.getVector(),currImage.getVector());
			distanceList.add(new ImageDistancePair(distance, currImage));
		}
		
		Collections.sort(distanceList);
		return distanceList;
	}
	
	public void regressImage(ImageData image,List<ImageData> imageSet, int k) {
		
		List<ImageDistancePair> distanceList = SortDistances(image,imageSet);
		double resultX = 0;
		double resultY = 0;
		double sum =0;
		double distance;
		
		for (int i = 0; i < Math.min(k,distanceList.size()); i++) {	
			distance = distanceList.get(i).getDistance();
			if (distance != 0) {
				resultX+=distanceList.get(i).getImage().getX() /distance;
				resultY+=distanceList.get(i).getImage().getY() /distance;
				sum+= 1/distance;
			} else {
				image.setXY(distanceList.get(i).getImage().getX(),distanceList.get(i).getImage().getY());
				imageSet.add(image);
				return;
			}
		}
		image.setXY(resultX/sum,resultY/sum);
		imageSet.add(image);
	}
}
